Calculate Median of Numbers

Theory:

The median of a list of numbers is the middle value when the numbers are sorted in ascending order. If the list has an odd number of elements, the median is the middle value. If the list has an even number of elements, the median is the average of the two middle values.

Python Code:

def calculate_median(numbers):
    sorted_numbers = sorted(numbers)
    n = len(sorted_numbers)
    if n % 2 == 0:
        return (sorted_numbers[n // 2 - 1] + sorted_numbers[n // 2]) / 2
    else:
        return sorted_numbers[n // 2]

# Taking input for numbers and calculating the median
def calculate_and_display_median():
    numbers = [float(x) for x in input("Enter numbers separated by spaces: ").split()]
    median = calculate_median(numbers)
    print("Median of the numbers:", median)

calculate_and_display_median()

Example Output 1:

Enter numbers separated by spaces: 3 5 1 9 7

Median of the numbers: 5.0

Example Output 2:

Enter numbers separated by spaces: 2 6 4 8 10 12

Median of the numbers: 7.0

Code Explanation:

The function calculate_median(numbers) calculates the median of a list of numbers by sorting them and determining the middle value or values.

The function calculate_and_display_median() takes input for numbers, calculates the median using the aforementioned function, and displays the result.